package com.send.queue;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.send.api.IMailService;
import com.send.config.BaseSend;
import com.send.config.EmailConfig;
@Component
public class ConsumeSendQueue {
	private static final Logger logger = LoggerFactory.getLogger(ConsumeSendQueue.class);
	@Autowired
	IMailService mailService;
	
	@PostConstruct
	public void startThread() {
		ExecutorService e = Executors.newFixedThreadPool(5);// 5个大小的固定线程池
		e.submit(new PollMail(mailService));
		e.submit(new PollMail(mailService));
		e.submit(new PollMail(mailService));
		e.submit(new PollMail(mailService));
		e.submit(new PollMail(mailService));
	}

	class PollMail implements Runnable {
		IMailService mailService;

		public PollMail(IMailService mailService) {
			this.mailService = mailService;
		}

		@Override
		public void run() {
			while (true) {
				logger.info("#############初始化完成#################" + Thread.currentThread().getName());
				try {
					BaseSend mail = SendQueue.getMailQueue().consume();
					if (mail != null) {
						logger.info("剩余邮件总数:{}", SendQueue.getMailQueue().size());
						EmailConfig config1 = (EmailConfig)mail;
						logger.info("邮件内容:{}", config1.getContent());
						if(mail instanceof EmailConfig){
							EmailConfig config = (EmailConfig)mail;
							mailService.sendHtml(config);
						}


					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	@PreDestroy
	public void stopThread() {
		logger.info("destroy");
	}
}
